<template>
  <div class="preview-panel" :class="{ 'is-fullscreen': isFullscreen }">
    <div class="preview-header" v-if="showHeader">
      <div class="header-left">
        <h3 class="preview-title">{{ title || '预览' }}</h3>
      </div>
      
      <div class="header-right">
        <el-button-group>
          <el-button
            :type="syncScroll ? 'primary' : 'default'"
            icon="el-icon-connection"
            size="mini"
            @click="toggleSyncScroll"
          >
            同步滚动
          </el-button>
          
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="refreshPreview"
          >
            刷新
          </el-button>
          
          <el-button
            icon="el-icon-copy-document"
            size="mini"
            @click="copyHtml"
          >
            复制HTML
          </el-button>
          
          <el-button
            :icon="isFullscreen ? 'el-icon-copy-document' : 'el-icon-full-screen'"
            size="mini"
            @click="toggleFullscreen"
          >
            {{ isFullscreen ? '退出全屏' : '全屏' }}
          </el-button>
        </el-button-group>
      </div>
    </div>
    
    <div class="preview-content" ref="previewContent">
      <div 
        class="markdown-body"
        v-html="renderedHtml"
        @scroll="handleScroll"
      ></div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="preview-loading">
      <loading-spinner text="渲染中..." />
    </div>
    
    <!-- 错误状态 -->
    <div v-if="error" class="preview-error">
      <empty-state
        icon="el-icon-warning"
        title="渲染失败"
        :description="error"
        action-text="重试"
        @action="refreshPreview"
      />
    </div>
  </div>
</template>

<script>
import { marked } from 'marked'
import hljs from 'highlight.js'
import katex from 'katex'
import mermaid from 'mermaid'
import { debounce, copyToClipboard } from '@/utils/helpers'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
import EmptyState from '@/components/common/EmptyState.vue'

export default {
  name: 'PreviewPanel',
  
  components: {
    LoadingSpinner,
    EmptyState
  },
  
  props: {
    // Markdown 内容
    content: {
      type: String,
      default: ''
    },
    
    // 标题
    title: {
      type: String,
      default: ''
    },
    
    // 是否显示头部
    showHeader: {
      type: Boolean,
      default: true
    },
    
    // 是否全屏
    isFullscreen: {
      type: Boolean,
      default: false
    },
    
    // 渲染选项
    options: {
      type: Object,
      default: () => ({
        codeHighlight: true,
        mathSupport: true,
        mermaidSupport: true,
        breaks: true,
        linkify: true
      })
    }
  },
  
  data() {
    return {
      renderedHtml: '',
      loading: false,
      error: null,
      syncScroll: true,
      scrollTimeout: null
    }
  },
  
  watch: {
    content: {
      handler: 'debouncedRender',
      immediate: true
    },
    
    options: {
      handler: 'renderMarkdown',
      deep: true
    }
  },
  
  created() {
    // 创建防抖渲染函数
    this.debouncedRender = debounce(this.renderMarkdown, 300)
    
    // 初始化 marked 配置
    this.initMarked()
    
    // 初始化 mermaid
    this.initMermaid()
  },
  
  methods: {
    // 初始化 marked 配置
    initMarked() {
      const renderer = new marked.Renderer()
      
      // 自定义代码块渲染
      renderer.code = (code, language) => {
        if (this.options.codeHighlight && language && hljs.getLanguage(language)) {
          try {
            const highlighted = hljs.highlight(code, { language }).value
            return `<pre class="hljs"><code class="language-${language}">${highlighted}</code></pre>`
          } catch (error) {
            console.warn('代码高亮失败:', error)
          }
        }
        return `<pre><code>${this.escapeHtml(code)}</code></pre>`
      }
      
      // 自定义链接渲染
      renderer.link = (href, title, text) => {
        const titleAttr = title ? ` title="${title}"` : ''
        return `<a href="${href}"${titleAttr} target="_blank" rel="noopener noreferrer">${text}</a>`
      }
      
      // 自定义图片渲染
      renderer.image = (href, title, text) => {
        const titleAttr = title ? ` title="${title}"` : ''
        const altAttr = text ? ` alt="${text}"` : ''
        return `<img src="${href}"${altAttr}${titleAttr} class="markdown-image" loading="lazy" />`
      }
      
      // 自定义表格渲染
      renderer.table = (header, body) => {
        return `<div class="table-wrapper"><table class="markdown-table">
<thead>
${header}</thead>
<tbody>
${body}</tbody>
</table></div>`
      }
      
      // 配置 marked
      marked.setOptions({
        renderer,
        breaks: this.options.breaks,
        gfm: true,
        sanitize: false
      })
    },
    
    // 初始化 mermaid
    initMermaid() {
      if (this.options.mermaidSupport) {
        mermaid.initialize({
          startOnLoad: false,
          theme: 'default',
          securityLevel: 'loose'
        })
      }
    },
    
    // 渲染 Markdown
    async renderMarkdown() {
      if (!this.content.trim()) {
        this.renderedHtml = '<div class="empty-content">开始编写您的文档...</div>'
        return
      }
      
      this.loading = true
      this.error = null
      
      try {
        let html = marked(this.content)
        
        // 处理数学公式
        if (this.options.mathSupport) {
          html = await this.renderMath(html)
        }
        
        // 处理 mermaid 图表
        if (this.options.mermaidSupport) {
          html = await this.renderMermaid(html)
        }
        
        this.renderedHtml = html
        
        // 下一帧更新 mermaid 图表
        this.$nextTick(() => {
          this.updateMermaidCharts()
        })
      } catch (error) {
        console.error('Markdown 渲染失败:', error)
        this.error = error.message || '渲染失败'
      } finally {
        this.loading = false
      }
    },
    
    // 渲染数学公式
    async renderMath(html) {
      // 行内公式
      html = html.replace(/\$([^$]+)\$/g, (match, formula) => {
        try {
          return katex.renderToString(formula, { displayMode: false })
        } catch (error) {
          console.warn('数学公式渲染失败:', formula, error)
          return match
        }
      })
      
      // 块级公式
      html = html.replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
        try {
          return katex.renderToString(formula, { displayMode: true })
        } catch (error) {
          console.warn('数学公式渲染失败:', formula, error)
          return match
        }
      })
      
      return html
    },
    
    // 渲染 mermaid 图表
    async renderMermaid(html) {
      const mermaidRegex = /```mermaid\s*\n([\s\S]*?)\n```/g
      let match
      const charts = []
      
      while ((match = mermaidRegex.exec(html)) !== null) {
        charts.push({
          original: match[0],
          code: match[1].trim(),
          id: `mermaid-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
        })
      }
      
      for (const chart of charts) {
        try {
          const svg = await mermaid.render(chart.id, chart.code)
          html = html.replace(chart.original, `<div class="mermaid-chart">${svg}</div>`)
        } catch (error) {
          console.warn('Mermaid 图表渲染失败:', chart.code, error)
          html = html.replace(chart.original, `<pre class="mermaid-error"><code>${this.escapeHtml(chart.code)}</code></pre>`)
        }
      }
      
      return html
    },
    
    // 更新 mermaid 图表
    updateMermaidCharts() {
      if (this.options.mermaidSupport) {
        const charts = this.$refs.previewContent.querySelectorAll('.mermaid')
        charts.forEach(chart => {
          if (!chart.dataset.processed) {
            mermaid.init(undefined, chart)
            chart.dataset.processed = 'true'
          }
        })
      }
    },
    
    // 转义 HTML
    escapeHtml(text) {
      const div = document.createElement('div')
      div.textContent = text
      return div.innerHTML
    },
    
    // 刷新预览
    refreshPreview() {
      this.renderMarkdown()
    },
    
    // 复制 HTML
    async copyHtml() {
      try {
        await copyToClipboard(this.renderedHtml)
        this.$message({
          message: 'HTML 已复制到剪贴板',
          type: 'success'
        })
      } catch (error) {
        this.$message({
          message: '复制失败',
          type: 'error'
        })
      }
    },
    
    // 切换同步滚动
    toggleSyncScroll() {
      this.syncScroll = !this.syncScroll
      this.$emit('sync-scroll-change', this.syncScroll)
    },
    
    // 切换全屏
    toggleFullscreen() {
      this.$emit('fullscreen-change', !this.isFullscreen)
    },
    
    // 处理滚动
    handleScroll(event) {
      if (this.syncScroll) {
        clearTimeout(this.scrollTimeout)
        this.scrollTimeout = setTimeout(() => {
          const element = event.target
          const scrollPercentage = element.scrollTop / (element.scrollHeight - element.clientHeight)
          this.$emit('scroll', scrollPercentage)
        }, 16) // 60fps
      }
    },
    
    // 滚动到指定位置
    scrollToPercentage(percentage) {
      if (this.syncScroll && this.$refs.previewContent) {
        const element = this.$refs.previewContent.querySelector('.markdown-body')
        if (element) {
          const scrollTop = (element.scrollHeight - element.clientHeight) * percentage
          element.scrollTop = scrollTop
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.preview-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
  border-left: 1px solid #e8e8e8;
  
  &.is-fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    border: none;
  }
}

.preview-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
  background: #fafafa;
  
  .preview-title {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
  }
}

.preview-content {
  flex: 1;
  overflow: auto;
  position: relative;
  
  .markdown-body {
    padding: 20px;
    line-height: 1.6;
    color: #333;
    
    // 标题样式
    h1, h2, h3, h4, h5, h6 {
      margin: 1.5em 0 0.5em 0;
      font-weight: 600;
      line-height: 1.4;
      
      &:first-child {
        margin-top: 0;
      }
    }
    
    h1 { font-size: 2em; border-bottom: 1px solid #eee; padding-bottom: 0.3em; }
    h2 { font-size: 1.5em; border-bottom: 1px solid #eee; padding-bottom: 0.3em; }
    h3 { font-size: 1.25em; }
    h4 { font-size: 1em; }
    h5 { font-size: 0.875em; }
    h6 { font-size: 0.85em; color: #666; }
    
    // 段落样式
    p {
      margin: 0 0 1em 0;
    }
    
    // 列表样式
    ul, ol {
      margin: 0 0 1em 0;
      padding-left: 2em;
      
      li {
        margin: 0.25em 0;
      }
    }
    
    // 引用样式
    blockquote {
      margin: 1em 0;
      padding: 0.5em 1em;
      border-left: 4px solid #ddd;
      background: #f9f9f9;
      color: #666;
      
      p {
        margin: 0;
      }
    }
    
    // 代码样式
    code {
      padding: 0.2em 0.4em;
      background: #f1f1f1;
      border-radius: 3px;
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      font-size: 0.9em;
    }
    
    pre {
      margin: 1em 0;
      padding: 1em;
      background: #f8f8f8;
      border-radius: 4px;
      overflow-x: auto;
      
      code {
        padding: 0;
        background: none;
        border-radius: 0;
      }
    }
    
    // 表格样式
    .table-wrapper {
      overflow-x: auto;
      margin: 1em 0;
      
      .markdown-table {
        width: 100%;
        border-collapse: collapse;
        
        th, td {
          padding: 8px 12px;
          border: 1px solid #ddd;
          text-align: left;
        }
        
        th {
          background: #f5f5f5;
          font-weight: 600;
        }
        
        tr:nth-child(even) {
          background: #f9f9f9;
        }
      }
    }
    
    // 图片样式
    .markdown-image {
      max-width: 100%;
      height: auto;
      border-radius: 4px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    // 分割线样式
    hr {
      margin: 2em 0;
      border: none;
      border-top: 1px solid #eee;
    }
    
    // 链接样式
    a {
      color: #409eff;
      text-decoration: none;
      
      &:hover {
        text-decoration: underline;
      }
    }
    
    // Mermaid 图表样式
    .mermaid-chart {
      text-align: center;
      margin: 1em 0;
      
      svg {
        max-width: 100%;
        height: auto;
      }
    }
    
    .mermaid-error {
      background: #fff2f0;
      border: 1px solid #ffccc7;
      color: #a8071a;
    }
    
    // 空内容样式
    .empty-content {
      text-align: center;
      color: #999;
      font-style: italic;
      padding: 2em;
    }
  }
}

.preview-loading,
.preview-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
}

// 响应式设计
@media (max-width: 768px) {
  .preview-header {
    flex-direction: column;
    gap: 8px;
    
    .header-right {
      width: 100%;
      
      .el-button-group {
        width: 100%;
        display: flex;
        
        .el-button {
          flex: 1;
          font-size: 12px;
        }
      }
    }
  }
  
  .preview-content {
    .markdown-body {
      padding: 12px;
      font-size: 14px;
    }
  }
}
</style>